<template>
  <div>
    <h1>三级分类页面</h1>

    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>

    <el-switch
      v-model="draggable"
      active-color="#13ce66"
      inactive-color="#ff4949"
    >
    </el-switch>
    开启拖拽

    <el-tree
      ref="menuTree"
      @node-click="nodeclick"
      :filter-node-method="filterNode"
      :highlight-current="true"
      @node-drop="nodeDrop"
      node-key="catId"
      :draggable="draggable"
      :allow-drop="allowDrop"
      :default-expanded-keys="defaultExpandedKeys"
      :data="dataList"
      :props="defaultProps"
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel != 3"
            type="text"
            size="mini"
            @click="
              form = {};
              append(data);
            "
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="update(data)">
            update
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="三级分类编辑" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="活动名称" label-width="120px">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      filterText: "",

      expandedKey: [],

      upadteNodes: [],
      level: 1,
      pid: 0,
      draggable: false,
      countLevel: 1,
      defaultExpandedKeys: [],
      form: {
        sort: 0,
      },
      dialogFormVisible: false,
      dataList: [],

      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.menuTree.filter(val);
    },
  },

  created() {
    this.getDataList();
  },
  methods: {
    //树节点过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    nodeclick(data, node, component) {
      console.log("子组件category的节点被点击", data, node, component);
      //向父组件发送事件；
      this.$emit("tree-node-click", data, node, component);
    },

    nodeDrop(draggingNode, dropNode, type) {
      //console.log("拖拽结束",draggingNode,dropNode,type)
      if (type == "before" || type == "after") {
        this.pid = dropNode.data.parentCid;
        this.level = dropNode.level;
        if (dropNode.level == 1 && draggingNode.level == 2) {
          this.collectNodes(
            dropNode.parent.childNodes,
            true,
            draggingNode.childNodes
          );
        } else {
          this.collectNodes(dropNode.parent.childNodes);
        }
      } else if (type == "inner") {
        this.pid = dropNode.data.catId;
        this.level = dropNode.level + 1;
        this.collectNodes(dropNode.childNodes);
        //因为本身不存在单独的二级分类，所以可以不判断
      }
      console.log("修改的对象", this.upadteNodes);
      this.$http({
        url: this.$http.adornUrl(`/product/category/updatesNodes`),
        method: "post",
        data: this.$http.adornData(this.upadteNodes, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "拖拽成功",
            type: "success",
          });
          this.getDataList();
          this.upadteNodes = [];
        }
      });
    },
    collectNodes(nodes, flag = false, nodes2) {
      // console.log("从新收集的对象", nodes);
     
      for (var i = 0; i < nodes.length; i++) {
        let obj = {
          catId: nodes[i].data.catId,
          parentCid: this.pid,
          sort: i,
          catLevel: this.level,
          name: nodes[i].data.name,
        };
        this.upadteNodes.push(obj);
      }
      if (flag) {
        for (var i = 0; i < nodes2.length; i++) {
          let o = {
            catId: nodes2[i].data.catId,

            sort: i,
            catLevel: this.level + 1,
            name: nodes2[i].data.name,
          };
          this.upadteNodes.push(o);
        }
      }
      // console.log(this.upadteNodes)
    },

    //判断目标对象是否可以被放置 type：'prev'、'inner' 和 'next'
    //draggingNode
    // dropNode目标对象  true可以拖拽

    //不能大于三层
    //拖拽对象和目标对象的层级的和小于3

    allowDrop(draggingNode, dropNode, type) {
      //console.log(draggingNode,dropNode,type)
      //1.计算层级
      this.getCountLevel(draggingNode);
      //console.log("被拖拽的层数是"+this.countLevel);
      if (type == "next" || type == "prev") {
        if (this.countLevel == 1) return true;
        if (this.countLevel == 2 && dropNode.level != 3) return true;
        if (this.countLevel == 3 && dropNode.level == 1) return true;
      } else if (type == "inner") {
        if (this.countLevel == 1 && dropNode.level != 3) return true;
        if (this.countLevel == 2 && dropNode.level == 1) return true;
      }

      return false;
    },
    getCountLevel(node) {
      this.countLevel = 1;
      if (node.childNodes.length > 0) {
        this.countLevel = 2;
        for (var i in node.childNodes) {
          if (node.childNodes[i].childNodes.length > 0) {
            this.countLevel = 3;
            return;
          }
        }
      }
    },

    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/product/category/tree/list"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        this.dataList = data.data;
      });
    },
    append(data) {
      console.log(data);
      this.dialogFormVisible = true;
      this.form.parentCid = data.catId;
      this.form.catLevel = data.catLevel + 1;
    },
    remove(node, data) {
      console.log(node, data);
      let ids = [data.catId];
      this.$http({
        url: this.$http.adornUrl(`/product/category/delete`),
        method: "post",
        data: this.$http.adornData(ids, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getDataList();
          this.defaultExpandedKeys = [this.form.parentCid];
        }
      });
    },
    save() {
      console.log(this.form);
      let methodurl = "save";
      if (this.form.catId) {
        methodurl = "update";
      }

      this.$http({
        url: this.$http.adornUrl(`/product/category/${methodurl}`),
        method: "post",
        data: this.$http.adornData(this.form, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });

          this.dialogFormVisible = false;
          this.getDataList();
          this.defaultExpandedKeys = [this.form.parentCid];
        }
      });
    },
    //修改
    update(data) {
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.form = data.category;
      });
    },
  },
};
</script>
